<?php
header('Content-Type:text/html; charset=UTF-8');
	$con =  mysql_connect('localhost:3306','root','zhzest2016');
		mysql_select_db("ustore", $con);
		mysql_query("set character set 'utf8'");//读库 
		mysql_query("set names 'utf8'");//写库 
		if (!$con)
		{
		  die('Could not connect: ' . mysql_error());
		}

if($_GET['Notify']==1){
	Notify();
	die;
}
		
if($_POST['fun']=="findCustomerByNo"){
	findCustomerByNo($_POST['customerNo']);
}elseif($_POST['fun']=="findGoodsByNo"){
	findGoodsByNo($_POST['customerNo'],$_POST['goodsNo']);
}elseif($_POST['fun']=="addOrder"){
	addOrder($_POST['json']);
}elseif($_POST['fun']=="Openid"){
	Openid($_POST['code']);
}elseif($_POST['fun']=="orderlist"){
	orderlist($_POST['openid']);
}elseif($_POST['fun']=="cs"){
	cs();
}else{
	die;
}
/*
获取网点信息
输入：customerNo:网点编号
输出：jason串：{success：0/1 ；id:主键; name:网点名称; company:企业名称; }
存在该网点时，success返回1，其他情况返回0。
*/
 
function findCustomerByNo($customerNo){
$contact = mysql_fetch_row(mysql_query("select id,name,company,number from ci_contact where number='".$customerNo."'"));
if($contact[0]>0){
	echo json_encode(array('customerNo'=>$contact[3],'id'=>$contact[0],'name'=>$contact[1],'company'=>$contact[2],'success'=>1));
}else{
	echo json_encode(array('success'=>0));
}
 die;
}




/*
获取网点商品信息
输入：customerNo:网点编号；goodsNo:商品SKU编号
输出：jason串：{success：0/1 ；customerNo:网点编号;goodsNo:商品SKU编号;name:商品名称; price:商品单价;}
存在该商品时，success返回1，其他情况返回0。
*/
function findGoodsByNo($customerNo,$goodsNo){

//$goods = mysql_fetch_row(mysql_query("select contactNumber,goodsNumber,salePrice from ci_wdgoods where contactNumber='".$customerNo."' and goodsNumber = '".$goodsNo."'"));
$good = mysql_fetch_row(mysql_query("select id,name,salePrice from ci_goods where number='".$goodsNo."'"));
$img = mysql_fetch_row(mysql_query("select url from ci_goods_img where invId=".$good[0]));
if($good[0]!=""){
	echo json_encode(array('customerNo'=>$customerNo,'goodsNo'=>$goodsNo,'img'=>$img[0],'name'=>$good[1],'price'=>$good[2],'success'=>1));
}else{
	echo json_encode(array('success'=>0));
}
 die;
}
/*
新增订单<插入主表&子表>
输入：jason{全部订单信息插入主表&子表}
输出：jason串：{success：0/1 ；remark：失败原因}
*/
function addOrder($json){
	$goods=json_decode($json,true);//得到返回的数组
	
	$times=time();//初始化一个时间
	$Body    = "海鸥淘";//商家名称
	$OrderNo = date('YmdHis',$times).rand(1000,9999);//生成唯一订单号
	$Total_fee = $goods[1]['goodsAmount'];//订单金额
	$Notify_url = "https://erp.mod-softs.com/Notify.php";//后台通知地址
	$Openid  = $goods[0]['userId'];// Openid
	$arr=array(
		'userId'=>$goods[0]['userId'],
		'orderStatus'=>0,
		'payStatus'=>0,
		'payName'=>'微信支付',
		'goodsAmount'=>$goods[1]['goodsAmount'],
		'moneyPaid'=>$goods[1]['goodsAmount'],
		'createTime'=>$times,
		'goodslist'=>$goods[2]['carts'],
	);
	//$json=json_encode($order);
	//$arr=json_decode($json,true);//得到返回的数组
	$error;
	if(!mysql_query("INSERT INTO ci_wx_order(orderSN,userId,orderStatus,payStatus,payName,goodsAmount,moneyPaid,createTime) VALUES ('$OrderNo','$arr[userId]',$arr[orderStatus],$arr[payStatus],'$arr[payName]',$arr[goodsAmount],$arr[moneyPaid],'$arr[createTime]')")){
		$error="订单主表插入失败";
	}
	$i=0;
	foreach($arr['goodslist'] as $ls){
		$customer=$ls['customerNo'];
		$good=$ls['goodsNo'];
	if(!mysql_query("INSERT INTO ci_wx_order_goods(orderSN,customerNumber,goodsNumber,goodsName,num,goodsPrice) VALUES ('$OrderNo','$customer','$good','$ls[title]',$ls[num],$ls[price])")){
		$error.="订单商品表第".$i."个商品插入失败";
	}
	$i++;
 }
	if($error==""||$error==null){
		require_once('pay.php');
		$WxPay = new WXPay();
		$Total_fee = $Total_fee * 100;
		$parameters = $WxPay->index($Body,$OrderNo,$Total_fee,$Notify_url,$Openid); 
		$shuzu=json_decode($parameters,true);//得到返回的数组
		$paySign = $shuzu['paySign'];
		if(mysql_query("UPDATE ci_wx_order SET wxpaystring = '$parameters',paySign = '$paySign' WHERE  orderSN ='$OrderNo'" )){
			echo $parameters;
		}
		//echo json_encode(array('success'=>1,'remark'=>"OK"));
	}else{
		echo json_encode(array('success'=>0,'remark'=>$error));
	}
	die;
}
function Openid($code){
		$appid="wx6d0679b11da9a628";
		$appsecret="9fe4d75c618996538852cd0500c6ebe9";
	    $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=". 
        $appsecret."&code=".$code."&grant_type=authorization_code";
        $weixin=file_get_contents($url);//通过code换取网页授权access_token
        $jsondecode=json_decode($weixin); //对JSON格式的字符串进行编码
        $array = get_object_vars($jsondecode);//转换成数组
        $openid = $array['openid'];//输出openid
        echo $openid;die;
}
function Notify(){
	$paytime = time();
	$paySign = $_POST['paySign'];
	$error;
	$payStatus = mysql_fetch_row(mysql_query("select payStatus from ci_wx_order where paySign='$paySign'"));
	if($payStatus[0]==1){
		echo json_encode(array('success'=>1,'remark'=>"OK"));
		die;
	}
	if(mysql_query("UPDATE ci_wx_order SET payStatus = 1,orderStatus = 1,payTime = '$paytime' WHERE  paySign ='$paySign'")){
		$wx_order = mysql_fetch_row(mysql_query("select orderSN from ci_wx_order where paySign='$paySign'"));
		$orderSN = $wx_order[0];
		if(mysql_query("UPDATE ci_wx_order_goods SET payStatus = 1 WHERE  orderSN ='$orderSN'")){
			echo json_encode(array('success'=>1,'remark'=>"OK"));
		}else{
		$error="订单子表插入失败";
		echo json_encode(array('success'=>0,'remark'=>$error));
		}
	}else{
		$error="订单主表插入失败";
		echo json_encode(array('success'=>0,'remark'=>$error));
	}
	$handle=fopen("post.txt","a+");
	$str=fwrite($handle,$paySign."\n");
	fclose($handle);
	die;

}
//订单列表
function orderlist($openid){
	
	$ci_wx_order=mysql_query("select orderSN,createTime,goodsAmount,orderStatus from ci_wx_order where userId='".$openid."' order by id desc");
	$i=0;
	$arr;
	while($order=mysql_fetch_array($ci_wx_order)) 
    {
			$arr[$i]['orderSN']=$order['orderSN'];
			$arr[$i]['goodsAmount']=$order['goodsAmount'];
			$arr[$i]['createTime']=date('Y-m-d H:i:s',$order['createTime']+8*3600);
			$result=mysql_query("select * from ci_wx_order_goods where orderSN ='".$order['orderSN']."'");
		    if($order['orderStatus']==1){
			   $arr[$i]['status']=true;
		    }else{
			   $arr[$i]['status']=false;
		    }
			$j=0;
			while($row=mysql_fetch_array($result)) 
			{
			  
			   $good = mysql_fetch_row(mysql_query("select id from ci_goods where number='".$row['goodsNumber']."'"));
			   $img = mysql_fetch_row(mysql_query("select url from ci_goods_img where invId=".$good[0]));
			   
			   $arr[$i]['goodlist'][$j]['img']=$img[0];
			   $arr[$i]['goodlist'][$j]['orderSN']=$row['orderSN'];
			   $arr[$i]['goodlist'][$j]['goodsName']=$row['goodsName'];
			   $arr[$i]['goodlist'][$j]['num']=$row['num'];
			   $arr[$i]['goodlist'][$j]['goodsPrice']=$row['goodsPrice'];
			   $arr[$i]['goodlist'][$j]['numPrice']=$row['num']*$row['goodsPrice'];
			  $j++;
			}
		$i++;
	}
	echo json_encode(array('success'=>0,'arr'=>$arr));
	die;
}
function cs(){
	sleep(9);
	echo json_encode(array('success'=>0,'remark'=>'no'));
}
?>